#define  _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
//环形子数组的最大和
//主要是没想到转换成线性数组的最大和，太巧秒了
//需要注意的是最后的比较情况，如果sum-gmin == 0肯定是不存在，这个需要考虑好
class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();

        //创建dp表
        vector<int> f(n + 1);
        auto g = f;
        int fmax = nums[0], gmin = nums[0];
        //填表
        for (int i = 1; i <= n; i++)
        {
            f[i] = max(nums[i - 1], f[i - 1] + nums[i - 1]);
            fmax = max(fmax, f[i]);
        }
        for (int i = 1; i <= n; i++)
        {
            g[i] = min(nums[i - 1], g[i - 1] + nums[i - 1]);
            gmin = min(gmin, g[i]);
        }
        //返回值
        int sum = 0;
        for (int i = 0; i < n; i++) sum += nums[i];

        return ((sum - gmin) == 0) ? fmax : max(fmax, sum - gmin);

    }
};
//一个循环就可以填完，代码进一步简化；
class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        //创建dp表
        vector<int> f(n + 1), g(n + 1);
        //填表
        int fmax = INT_MIN, gmin = INT_MAX, sum = 0;

        for (int i = 1; i <= n; i++)
        {
            int x = nums[i - 1];
            f[i] = max(x, f[i - 1] + x);
            fmax = max(fmax, f[i]);
            g[i] = min(x, g[i - 1] + x);
            gmin = min(gmin, g[i - 1]);
            sum += x;
        }

        return sum == gmin ? fmax : max(fmax, sum - gmin);
    }
};
int main()
{
	return 0;
}
